// pages/dt/submit.js
const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    type: 0,
    detail: {},
    winWidth: 0,
    winHeight: 0,
    latitude: 0,
    longitude: 0,
    position: '',
    imageList: [],
    videoSrc: '',
    showLoading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var id = options.id;
    if (id) {
      that.setData({
        id: id,
      });

      that.loadData();
    }

    var type = options.type;
    if (type) {
      that.setData({
        type: type,
      });
    }

    var title = options.title;
    if (title) {
      wx.setNavigationBarTitle({
        title: title,
      })
    }

    /**
     * 获取系统信息
     */
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    // wx.getLocation({
    //   type: 'wgs84',
    //   success: function (res) {
    //     var latitude = res.latitude
    //     var longitude = res.longitude

    //     console.log(res);

    //     wx.setStorageSync("latitude", latitude);
    //     wx.setStorageSync("longitude", longitude);

    //     that.setData({
    //       latitude: latitude,
    //       longitude: longitude
    //     });

    //     that.getAddr(latitude + "," + longitude);
    //   },
    //   fail: function (err) {
    //     console.log("err:" + err);
    //   }
    // })
  },
  chooseLocation: function () {
    var that = this;
    var latitude = wx.getStorageSync("latitude");
    var longitude = wx.getStorageSync("longitude");

    wx.chooseLocation({
      latitude: latitude,
      longitude: longitude,
      success(res) {
        console.log(res);
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          position: res.address,
        });
      }
    });
  },
  getAddr: function (localStr) {
    var that = this;
    var apiUrl = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=GGjOzDmyjbSEjLKYfIaKFnquYjVn6gHD&output=json&coordtype=wgs84ll&location=" + localStr;

    http.ApiGet(apiUrl, {}, function (res) {
      if (res.status == 0) {

        var position = res.result.formatted_address;

        that.setData({
          position: position
        });
      }
    });
  },
  loadData: function () {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.id;

    http.ApiGet(apiUrl.UrlNewsDetail, parameter, function (res) {
      if (res.result.errorCode == 1) {

        var detail = res.data;

        that.setData({
          type: detail.show_type,
          imageList: detail.images,
          videoSrc: detail.video,
          detail: detail,
        });
      } else {
        wx.showModal({
          title: res.result.errorMessage
        });
      }
    });
  },
  chooseImage: function () {
    var that = this
    wx.chooseImage({
      count: 9,
      success: function (res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j])
        }
      }
    })
  },
  uploadImage: function (path) {
    var that = this
    that.showLoading();
    var postData = {};
    var token = wx.getStorageSync("token");
    postData["token"] = token;
    wx.uploadFile({
      url: apiUrl.UrlUpload,
      filePath: path,
      name: 'file',
      formData: postData,
      success: function (res) {
        that.cancelLoading();
        var resdata = JSON.parse(res.data);
        var result = resdata.result;
        if (result.errorCode == 1) {
          wx.hideToast();

          that.setData({
            imageList: that.data.imageList.concat(resdata.url)
          })
        } else {
          wx.showModal({
            title: result.errorMessage
          });
        }
      },
      fail: function (err) {
        console.log(err);
        that.cancelLoading();
        wx.showModal({
          title: '上传出错！'
        });
      }
    })
  },
  imageTapAction: function (e) {
    var index = e.target.dataset.id
    var that = this
    // console.log(index);
    wx.showActionSheet({
      itemList: ['查看', '删除'],
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            // console.log("查看")
            that.previewImage(index);
          } else if (res.tapIndex == 1) {
            // console.log("删除");
            wx.showModal({
              title: '确定删除？',
              content: '',
              success: function (res) {
                if (res.confirm) {
                  that.delImage(index);
                }
              }
            })
          }
        }
      }
    })
  },
  delImg: function (e) {
    var index = e.target.dataset.id
    var that = this

    wx.showModal({
      title: '确定删除？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          that.delImage(index);
        }
      }
    })
  },
  previewImage: function (index) {
    var current = this.data.imageList[index];
    wx.previewImage({
      current: current,
      urls: this.data.imageList
    })
  },
  delImage: function (index) {
    // console.log("delImage in (" + index + ",1)");
    var imageList = this.data.imageList;

    imageList.splice(index, 1);

    // console.log(imageList);

    this.setData({
      imageList: imageList,
    })
  },
  chooseVideo: function () {
    var that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      success: function (res) {
        // console.log(res)
        that.uploadVideo(res.tempFilePath);
      }
    })
  },
  uploadVideo: function (path) {
    var that = this
    that.showLoading();
    var postData = {};
    var token = wx.getStorageSync("token");
    postData["token"] = token;
    wx.uploadFile({
      url: apiUrl.UrlUpload,
      filePath: path,
      name: 'file',
      formData: postData,
      success: function (res) {
        that.cancelLoading();
        var resdata = JSON.parse(res.data);
        var result = resdata.result;
        if (result.errorCode == 1) {
          wx.hideToast();
          that.setData({
            videoSrc: resdata.url
          })
        } else {
          wx.showModal({
            title: result.errorMessage
          });
        }
      },
      fail: function (err) {
        console.log(err);
        that.cancelLoading();
        wx.showModal({
          title: '上传出错！'
        });
      }
    })
  },
  delVideo: function () {
    var that = this
    wx.showModal({
      title: '确定删除？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          that.setData({
            videoSrc: ''
          })
        }
      }
    })
  },
  showLoading: function () {
    this.setData({
      showLoading: true
    })
  },
  cancelLoading: function () {
    this.setData({
      showLoading: false
    })
  },
  submit: function (e) {
    var that = this;
    var formData = {};
    // console.log(e.detail.value);

    var title = e.detail.value.title;
    if (title == "") {
      wx.showModal({
        title: '请填写标题',
        content: ''
      });
      return;
    }
    formData['title'] = title;

    formData['type'] = that.data.type;

    if(that.data.id>0){
      formData['id'] = that.data.id;
    }

    var content = e.detail.value.content;
    if (content == "") {
      wx.showModal({
        title: '请填写内容',
        content: ''
      });
      return;
    }
    formData['content'] = content;
    formData['appId'] = util.APPID;
    formData['openId'] = wx.getStorageSync("openId");
    formData['address'] = that.data.position;

    wx.showToast({
      title: '正在提交',
      icon: 'loading',
      duration: 10000,
      mask: true,
    });

    //图片
    var image = '';
    var imgsList = that.data.imageList;
    if (imgsList.length > 0) {
      image = imgsList[0];
      if (imgsList.length > 1) {
        for (let j = 1; j < imgsList.length; ++j) {
          image += "," + imgsList[j];
        }
      }
    }
    formData['images'] = image;

    // var videoSrc = that.data.videoSrc;
    // if (videoSrc.length > 0) {
    //   formData['video'] = videoSrc;
    // }
    console.log(formData);

    http.ApiPost(apiUrl.UrlNewsSubmit, formData, function (res) {
      console.log(res.msg);
      if (res.result.errorCode == 1) {
        wx.showToast({
          title: res.result.errorMessage,
          icon: 'none'
        });
        wx.setStorageSync("refreshList", "dt");
        wx.navigateBack();
      } else {
        wx.showModal({
          title: res.result.errorMessage
        });
      }
    });
  },
})